package com.txby.platformApi.component.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jck.mybatis.log.GlobalLogAnnotation;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ChkUtil;
import com.txby.platformCore.component.service.CommonController;
import com.txby.platformCore.data.CommonApiModelMapExt;
import com.txby.platformCore.entity.SickBaseInfo;
import com.txby.platformCore.entity.SickCheckInfo;
import com.txby.platformCore.entity.SickCheckResultInfo;
import com.txby.platformCore.entity.SickDetailInfo;
import com.txby.platformCore.entity.TxbyBDApiConfig;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 患者信息
* @author 作者 jacking
* @date  
 */
@SuppressWarnings("all")
@RestController
@Api(value="患者信息",description="患者信息-说明")
@RequestMapping("/sickInfo")
public class SickInfoController extends CommonController{
	private static Logger log = Logger.getLogger(SickInfoController.class);
	
	@ApiOperation(value = "查询患者的检验信息", notes = "查询患者的检验信息-说明")
	@GetMapping("/getSickCheckResultInfo/{type}/{token}")
//	@ApiImplicitParams({
//		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
//		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true),
//		@ApiImplicitParam(paramType="query",dataType="string",name="bedNO",value="患者床号",required=true),
//		@ApiImplicitParam(paramType="query",dataType="string",name="sickAreaNO",value="床位病区号",required=true)
//	})
	@GlobalLogAnnotation(logType=2,discription="查询患者的检验信息")
	public Map getSickCheckResultInfo(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true)String deviceSN) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			if(token.startsWith("demo:")){
				deviceSN=demoDeviceSN;
			}
			Map paramMap = new HashMap<>();
			SickDetailInfo sdi=this.getSickDetailInfo(deviceSN);
			if(sdi==null){
				mm.put(CommonApiModelMapExt.ERRCODE, 1);
				mm.put(CommonApiModelMapExt.ERRMSG, "患者不存在");
				mm.put("data", new ArrayList());
				return mm;
			}
			
//			searchSql += " order by inHosTime desc";//默认入院时间倒序
			PageList<SickCheckResultInfo> pl=new PageList<>();
//			查询job接口是否异常， 如果异常 则只取本地数据库
//			this.isHisErr(TxbyBDApiConfig.class.getName());
			List<SickCheckResultInfo> oInfoList=new ArrayList<>();
			if(propertySourceConfig.getIsExecuteHisHttp()!=null&&propertySourceConfig.getIsExecuteHisHttp().equals("true")&&!isHisErr&&!ChkUtil.isEmpty(sdi)){
				List<TxbyBDApiConfig> bdInfoList=this.getTxbyBDApiConfigInfo(TxbyBDApiConfig.class.getName());
				if(!ChkUtil.isEmptyAllObject(bdInfoList)){
					TxbyBDApiConfig bdInfo=bdInfoList.get(0);
					Map jo=JSON.parseObject(bdInfo.getApiParam());
					jo.put("bedNO", sdi.getBedNO());
					jo.put("sickAreaNO", sdi.getSickAreaNO());
//					{"bedNO": "$bedNO", "sickNO": "$sickNO"}
					String json=this.getHttpResponseContent(bdInfo.getApiBaseUrl()+bdInfo.getApiServletPath(), "get",jo);
					JSONObject jsonData=JSON.parseObject(json);
					CommonApiModelMapExt temp= new CommonApiModelMapExt();
					BeanUtils.copyProperties(temp, jsonData);
					
					if(temp.getCode()==1){
						Map dataO=new HashMap();
						SickCheckResultInfo oInfo=new SickCheckResultInfo();
						Object o=jsonData.get("data");
						if(!(o instanceof JSONArray)){
							BeanUtils.copyProperties(oInfo, o);
							oInfoList.add(oInfo);
						}else{
							List oList=(List) o;
							for(Object obj:oList){
								oInfo=new SickCheckResultInfo();
								BeanUtils.copyProperties(oInfo, obj);
								oInfoList.add(oInfo);
							}
							
							//保存数组
						}
						
					}
					
//				    循环处理
					for(SickCheckResultInfo sbi:oInfoList){
						List<SickBaseInfo> oldObj=this.mBaseDao.findBySql("select * from  "+mBaseDao.tableName(SickCheckResultInfo.class)+" where 1=1   ", SickCheckResultInfo.class, null);
						SickBaseInfo oInfo=new SickBaseInfo();
						if(oldObj.size()>0){
							oInfo= oldObj.get(0);
							String id=oInfo.getId();
							BeanUtils.copyProperties(oInfo, sbi);
							oInfo.setId(id);
							oInfo.setUpdateTime(new Date());
							this.mBaseDao.updateObject(oInfo);
						}else{
							this.mBaseDao.saveObject(sbi);
						}
					}
					
				}
				pl =new PageList<>(oInfoList, null);
			}else{
				String sql="select * from (select d.hisItemName, d.unit,d.isValue,d.reaultFlag,d.rangeInfo,d.reportValue,d.reportFlag,d.valueData,d.parentId,d.id_ id_,(select  p.checkDay from t_txby_sickCheckResultInfo p where p.id_= d.parentId   ) as checkDay,(select  p.hisCheckName from t_txby_sickCheckResultInfo p where p.id_= d.parentId   ) as hisCheckName " + 
						"from t_txby_sickCheckResultInfo d  where d.inHosNO='"+sdi.getInHosNO()+"' ) t where t.parentId<>0 order by t.checkDay desc, t.parentId desc ,t.reportFlag  desc ";
				
				pl = this.mBaseDao.findBySqlForPageList(sql, SickCheckResultInfo.class, null, paramMap);
//				pl = this.mBaseDao.findBySqlForPageList("select * from  "+mBaseDao.tableName(SickCheckResultInfo.class)+" where inHosNO='"+sdi.getInHosNO()+"' ", Map.class, null, paramMap);
			}
			
			List fartherList=new ArrayList();
			List subList=new ArrayList();
			List data=new ArrayList();
			
			Map  mapUnique=new HashMap();
			for(SickCheckResultInfo s1:pl.getResultList()) {
				if(s1.getParentId()==null) {
					continue;
					
				}
				int parentId=s1.getParentId();
				Date checkDay=s1.getCheckDay();
				String hisCheckName=s1.getHisCheckName();
				if(mapUnique.get(parentId)==null) {
					Map m1=new HashMap();
					m1.put("checkDay", checkDay);
					m1.put("hisCheckName", hisCheckName);
					mapUnique.put(parentId, m1);
					List tempList=new ArrayList();
					for(SickCheckResultInfo s2:pl.getResultList()) {
						if(s2.getParentId()!=null&&s2.getParentId()==parentId) {
							s2.setId_(null);
							s2.setStatus(null);
							s2.setHisCheckName(null);
							s2.setUpdateTime(null);
							s2.setCheckTime(null);
							s2.setCreateTime(null);
							s2.setCheckDay(null);
							s2.setCreater(null);s2.setUpdater(null);
							tempList.add(s2);
						}
					}
					s1.setParentId(null);
					m1.put("subitems", tempList);
					data.add(m1);
				}
				
			}
			
			if(data.size()>0){
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data", data);
			}else{
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "无数据");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		
		return mm;
	}
	
	
	
	@ApiOperation(value = "查询患者的检查信息", notes = "查询患者的检查信息-说明")
	@GetMapping("/getSickCheckInfo/{type}/{token}")
/*	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="bedNO",value="患者床号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="sickAreaNO",value="床位病区号",required=true)
	})*/
	@GlobalLogAnnotation(logType=2,discription="查询患者的检查信息")
	public Map getSickCheckInfo(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true)String deviceSN) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			if(token.startsWith("demo:")){
				deviceSN=demoDeviceSN;
			}
			Map paramMap = new HashMap<>();
			String searchSql = "";
//			searchSql += " order by inHosTime desc";//默认入院时间倒序
			PageList<SickCheckInfo> pl=new PageList<>();
//			查询job接口是否异常， 如果异常 则只取本地数据库
//			this.isHisErr(TxbyBDApiConfig.class.getName());
			List<SickDetailInfo> oInfoList=new ArrayList<>();
			SickDetailInfo sdi=this.getSickDetailInfo(deviceSN);
			if(sdi==null){
				mm.put(CommonApiModelMapExt.ERRCODE, 1);
				mm.put(CommonApiModelMapExt.ERRMSG, "患者不存在");
				mm.put("data", pl.getResultList());
				return mm;
			}
			if(propertySourceConfig.getIsExecuteHisHttp()!=null&&propertySourceConfig.getIsExecuteHisHttp().equals("true")&&!isHisErr&&sdi!=null){
				List<TxbyBDApiConfig> bdInfoList=this.getTxbyBDApiConfigInfo(TxbyBDApiConfig.class.getName());
				if(!ChkUtil.isEmptyAllObject(bdInfoList)){
					TxbyBDApiConfig bdInfo=bdInfoList.get(0);
					Map jo=JSON.parseObject(bdInfo.getApiParam());
					jo.put("bedNO", sdi.getBedNO());
					jo.put("sickAreaNO", sdi.getSickAreaNO());
//					{"bedNO": "$bedNO", "sickNO": "$sickNO"}
					String json=this.getHttpResponseContent(bdInfo.getApiBaseUrl()+bdInfo.getApiServletPath(), "get",jo);
					JSONObject jsonData=JSON.parseObject(json);
					CommonApiModelMapExt temp= new CommonApiModelMapExt();
					BeanUtils.copyProperties(temp, jsonData);
					
					if(temp.getCode()==1){
						Map dataO=new HashMap();
						SickDetailInfo oInfo=new SickDetailInfo();
						Object o=jsonData.get("data");
						if(!(o instanceof JSONArray)){
							BeanUtils.copyProperties(oInfo, o);
							oInfoList.add(oInfo);
						}else{
							List oList=(List) o;
							for(Object obj:oList){
								oInfo=new SickDetailInfo();
								BeanUtils.copyProperties(oInfo, obj);
								oInfoList.add(oInfo);
							}
							
							//保存数组
						}
						
					}
					
//				    循环处理
					for(SickDetailInfo sbi:oInfoList){
						List<SickDetailInfo> oldObj=this.mBaseDao.findBySql("select * from  "+mBaseDao.tableName(SickDetailInfo.class)+" where 1=1   "+searchSql, SickDetailInfo.class, paramMap);
						SickDetailInfo oInfo=new SickDetailInfo();
						if(oldObj.size()>0){
							oInfo= oldObj.get(0);
							String id=oInfo.getId();
							BeanUtils.copyProperties(oInfo, sbi);
							oInfo.setId(id);
							oInfo.setUpdateTime(new Date());
							this.mBaseDao.updateObject(oInfo);
						}else{
							this.mBaseDao.saveObject(sbi);
						}
					}
					
				}
				pl =new PageList(oInfoList, null);
			}else{
				
				String sql="select * from "+this.mBaseDao.tableName(SickCheckInfo.class)+"  where   inHosNO='"+sdi.getInHosNO()+"' order by checkDay desc ";
				pl = this.mBaseDao.findBySqlForPageList(sql, SickCheckInfo.class, null, null);
			}
			for(SickCheckInfo s:pl.getResultList()) {
				s.setId_(null);
			}
			/**
			 * 请求http数据api
			 */
			
			if(pl.getResultList().size()>0){
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data",pl.getResultList());
			}else{
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "无数据");
			}
			
			return mm;
			
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		
		return mm;
	}


}